package me.shiqiang.im;

import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.bean.ConsumerBean;
import com.aliyun.openservices.ons.api.bean.Subscription;
import me.shiqiang.im.config.RocketMqConsumerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.Map;


@EnableCircuitBreaker
@EnableFeignClients
@SpringCloudApplication
public class ImPushServerApplication {
	@Autowired
	private Map<String,MessageListener> consumerMap;



	public static void main(String[] args) {
		SpringApplication.run(ImPushServerApplication.class, args);
	}


	@Value("#{${com.tst.rocketmq.consumer.subscription}}")
	Map<String, String> consumerSubscription;

	@Bean(initMethod = "start", destroyMethod = "shutdown")
	public ConsumerBean createConsumerBean(RocketMqConsumerConfig config) {
		ConsumerBean consumerBean = new ConsumerBean();
		consumerBean.setProperties(config.getProperties());
		Map<Subscription, MessageListener> table = new HashMap<>();
		for (Map.Entry<String, String> consumerConfig : consumerSubscription.entrySet()) {
			if (consumerMap.containsKey(consumerConfig.getKey())) {
				MessageListener messageListener = consumerMap.get(consumerConfig.getKey());
				String[] configs = consumerConfig.getValue().split("#");
				Subscription subscription = new Subscription();
				subscription.setTopic(configs[0]);
				subscription.setExpression(configs[1]);
				table.put(subscription, messageListener);
			}
		}
		consumerBean.setSubscriptionTable(table);
		return consumerBean;
	}
}
